from django.shortcuts import render,HttpResponse,redirect
from app.models import *

# Create your views here.


def index(request):
    data = Book.objects.values("nid","name","price","pub_date","publish__name")
    return render(request,"app/index.html",{"data":data})

def del_book(request,id):
    Book.objects.filter(nid=id).delete()
    return redirect("/")

def add_book(request):
    if request.method == 'GET':
        publishs = Publish.objects.values("nid","name")
        authors = Author.objects.values("nid","name")
        return render(request,"app/addbook.html",{'publishs':publishs,"authors":authors})
    elif request.method =='POST':
        try:
            book = Book.objects.create(name=request.POST.get("name")
                                ,pub_date=request.POST.get('pubDate')
                                ,price=request.POST.get("price")
                                ,publish_id=request.POST.get("publish_id"))
            book.authors.add(*request.POST.get("author_ids"))
            return redirect("/")
        except Exception as e:
            return render(request, 'error.html', {'content': e})

    else:
        return render(request, "404.html")


def add_publish(request):
    if request.method == 'GET':
        return render(request, "app/addpublish.html")
    elif request.method =='POST':
        try:
            res = Publish.objects.create(name=request.POST.get('name'),add=request.POST.get('addr'),email=request.POST.get('email'))
            if res :
                return redirect('/')
            else:
                return render(request, 'error.html', {'content': '添加失败'})
        except Exception as e:
            return render(request,'error.html',{'content':e})
    else:
        return render(request, "404.html")

def add_author(request):
    if request.method =='GET':
        return render(request, "app/addauthor.html")
    elif request.method =='POST':
        try:
            res = AuthorDetail.objects.create(phone=request.POST.get('phone'),addr=request.POST.get('addr'))
            if res :
                Author.objects.create(name=request.POST.get('name'),authorDetail=res)
                return redirect('/')
            else:
                return render(request, 'error.html', {'content': '添加失败'})
        except Exception as e:
            return render(request, 'error.html', {'content': e})

    else:
        return render(request, "404.html")





